package com.z.security.service.impl;

import com.z.entity.AuRoles;
import com.z.entity.security.Admin;
import com.z.security.entity.SecurityAdmin;
import com.z.service.AuRightsService;
import com.z.service.AuRolesService;
import com.z.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailServiceIml implements UserDetailsService {

    @Autowired
    AuRightsService auRightsService;

    @Autowired
    AuRolesService auRolesService;

    @Autowired
    UsersService usersService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //根据账号名称查询AdminVO对象

        Admin admin = usersService.getAdminByLoginAcct(username);

        // 读取adminId
        Integer adminId = admin.getId();

        // 根据adminId查询角色信息
        List<AuRoles> assignedRoleList = auRolesService.getAssignedRoleByAdminId(adminId);

        // 根据 adminId 查询权限信息
        List<String> authNameList = auRightsService.getAssignedAuthNameByAdminId(adminId);

        // 创建集合对象用来存储 GrantedAuthority
        List<GrantedAuthority> authorities = new ArrayList<>();

         // 遍历 assignedRoleList 存入角色信息
        for (AuRoles role : assignedRoleList) {

            String roleName = "ROLE_" + role.getRoleName();

            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(roleName);

            authorities.add(simpleGrantedAuthority);
        }

         // 7.遍历 authNameList 存入权限信息
        for (String authName : authNameList) {

            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(authName);

            authorities.add(simpleGrantedAuthority);
            
        }

        // 封装 SecurityAdmin 对象

        SecurityAdmin securityAdmin = new SecurityAdmin(admin, authorities);

        System.out.println("loadUserByUsername");

        return securityAdmin;


    }
}
